<template>
    <div class="container">
        <div class="login-wraper">
            <h2>智能云点餐后台</h2>
            <el-form :model="user" :rules="rules" ref="loginRef" status-icon>
                <el-form-item prop="username">
                    <el-input v-model="user.username" placeholder="用户名">
                        <template #prefix>
                            <el-icon><User /></el-icon>
                        </template>
                    </el-input>
                </el-form-item>

                <el-form-item prop="password">
                    <el-input
                        v-model="user.password"
                        type="password"
                        placeholder="密码"
                    >
                        <template #prefix>
                            <el-icon><Lock /></el-icon>
                        </template>
                    </el-input>
                </el-form-item>

                <el-form-item prop="confirmPsw">
                    <el-input
                        v-model="user.confirmPsw"
                        type="password"
                        placeholder="确认密码"
                    >
                        <template #prefix>
                            <el-icon><Lock /></el-icon>
                        </template>
                    </el-input>
                </el-form-item>

                <el-form-item :prop="count >= 3?rules.verifyCode:''" v-show="count >= 3">
                    <el-input
                        v-model="user.verifyCode"
                        type="text"
                        placeholder="验证码"
                    >
                        <template #suffix>
                            <span
                                v-html="veryCode.data"
                                @click="getVeryCode"
                            ></span>
                        </template>
                    </el-input>
                </el-form-item>

                <el-form-item>
                    <el-button
                        :loading="isLoading"
                        type="primary"
                        @click="onLogin(loginRef)"
                        >登录</el-button
                    >
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup lang="ts">
import { RequesetVeryCode, RequestLogin } from '@/api/index'
import { User, Lock } from '@element-plus/icons-vue'
import { ref, type Ref, onMounted } from 'vue'
import type { FormInstance, ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import sha256 from 'js-sha256'
import { saveUserToStore } from '@/common/useStore'
import { useMenuStore } from '@/stores/menu'
import {ACCESS_TOKEN,REFRESH_TOKEN} from '@/utils/constant'
interface IUser {
    username: string
    password: string
    confirmPsw: string
    verifyCode: string
}

const user: Ref<IUser> = ref({
    username: 'zhousir',
    password: 'yg123',
    confirmPsw: 'yg123',
    verifyCode: '',
})
/**
 * 确定密码方法
 */
const validatePass2 = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入再次密码'))
    } else if (value !== user.value.password) {
        callback(new Error('两次输入密码不匹配!'))
    } else {
        callback()
    }
}
let count = ref<number>(0) //记录三次出错显示验证码
const loginRef = ref<FormInstance>()
const isLoading: Ref<boolean> = ref(false)
const rules = ref({
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    verifyCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
    confirmPsw: [{ validator: validatePass2, trigger: 'blur' }],
})
const veryCode: Ref<{ data: string; code: string }> = ref({
    data: '',
    code: '',
})
const router = useRouter()
const menuStore = useMenuStore()

onMounted(() => {
    getVeryCode()
})

/**
 * 生成验证码
 */
const getVeryCode = async () => {
    const data = await RequesetVeryCode()
    const { resultCode, resultInfo } = data
    if (resultCode === 1) {
        const { code, data } = resultInfo
        veryCode.value.data = data
        veryCode.value.code = code
    }
}

/**
 * 校验验证码
 */
const checkVeriyCode = () => {
    const inputCode = user.value.verifyCode
    if (inputCode !== veryCode.value.code) {
        ElMessage.error('验证码出错!')
        return true
    }
    return false
}

const bindLogin = async () => {
    const username = user.value.username
    const password = user.value.password
    let psw = sha256(password)
    const data = await RequestLogin(username, psw)
    const { resultCode, resultInfo, token,refrechToken } = data
    if (resultCode === 1) {
        // 登录成功之后的业务
        // 1. 保存token, 统一登录身份认证（路由拦截）, 网络axios请求拦截(后端根据请求头中携带的token，决定是否返回接口数据给你)
        localStorage.setItem(ACCESS_TOKEN, token)
        localStorage.setItem(REFRESH_TOKEN, refrechToken)

        // 保存角色id
        localStorage.setItem('ROLE_ID',resultInfo.role_id)
        // 2. 保存用户信息(昵称和头像) 主界面显示
        saveUserToStore({ nick: resultInfo.nick, url: resultInfo.headerimg })
        // 3. 根据角色id获取动态权限菜单列表
        menuStore.saveMenuList(resultInfo.role_id).then(() => {
            // 登录成功进入主界面
            router.replace('/home')
        })
        
    }else{
        ElMessage.error('用户名或密码出错!')
        count.value++
    }
}

/**
 * 登录
 * @param formEl
 */
const onLogin = (formEl: FormInstance | undefined) => {
    // 表单验证
    if (!formEl) return
    formEl.validate(valid => {
        if (valid) {
            if (count.value >=3 && checkVeriyCode()) {
                return
            }
            bindLogin()
        }
    })
}
</script>

<style scoped lang="scss">
.container {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-color: #2b3c4d;
    .login-wraper {
        width: 400px;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        text-align: center;
        h2 {
            color: white;
        }
        form {
            background-color: white;
            border-radius: 8px;
            padding: 30px 25px;
            .el-button {
                width: 100%;
                margin-top: 24px;
            }
        }
    }
}
</style>
